package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private KafkaService kafkaService;

    @Override
    public void savePaymentInfo(String paymentType, Long userId, String orderNo, BigDecimal totalAmount) {

        //  可以利用 orderNo 去重操作...
        //  创建对象
        PaymentInfo paymentInfo = new PaymentInfo();
        //  属性赋值：
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setAmount(totalAmount);
        String content = paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)?"支付订单": "支付充值";
        paymentInfo.setContent(content);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //  保存数据
        paymentInfoMapper.insert(paymentInfo);
    }

    @Override
    public void updatePaymentStatus(Transaction result) {
        //  先修改paymentInfo 状态.
        PaymentInfo paymentInfoQuery = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, result.getOutTradeNo()));
        paymentInfoQuery.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfoQuery.setOutTradeNo(result.getTransactionId());
        paymentInfoQuery.setCallbackTime(new Date());
        paymentInfoQuery.setCallbackContent(result.toString());
        paymentInfoMapper.updateById(paymentInfoQuery);
        //  发送消息修改订单状态或充值状态.
        String topics = paymentInfoQuery.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER)? KafkaConstant.QUEUE_ORDER_PAY_SUCCESS:KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS;
        //  发送消息。
        kafkaService.sendMsg(topics,result.getOutTradeNo());
    }
}
